﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Architecture.Linq;
using System.Data.Linq;
using Emerald.Business.Controllers;

namespace Emerald.Business
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Role
    {
        private MembershipController m_membershipController;
        private JunctionList<Membership, User> m_users;

        private MembershipController MembershipController
        {
            get
            {
                if (m_membershipController == null)
                {
                    m_membershipController = new MembershipController();
                }

                return m_membershipController;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public JunctionList<Membership, User> Users
        {
            get
            {
                if (m_users == null)
                {
                    m_users = new JunctionList<Membership, User>(
                        this.Memberships,
                        ur => ur.User,
                        (ur, u) => ur.Add(new Membership { User = u, Role = this }),
                        delegate(IList<Membership> urs, User u)
                        {
                            Membership toRemove = urs.Where(ur => ur.User.Id == u.Id).Single();
                            MembershipController.Delete(toRemove);
                        }
                    );
                }

                return m_users;
            }
        }
    }
}
